//
//  StatusPictureView.swift
//  我的微博
//
//  Created by Creator on 15/10/16.
//  Copyright © 2015年 Creator. All rights reserved.
//

import UIKit
import SDWebImage


 /// 可重用 cell
private let StatusPictureViewCellID = "StatusPictureViewCellID"

///  配图视图
class StatusPictureView: UICollectionView {

     /// 数据模型
    var status: Status? {
        didSet {
        
            sizeToFit()
            
            // 刷新配图
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        

        return  calcViewSize()
    }
    
    // 计算视图大小
    private func calcViewSize() -> CGSize {
        
        // 准备常量
        let itemSize = CGSize(width: 90, height: 90)
        let margin: CGFloat = 10
        
        // 每一行最多显示的图片数量
        let rowCount = 3
        
        pictureLayout.itemSize = itemSize
    
        // 根据图片的数量计算视图大小
        let count = status!.pictureURLs?.count ?? 0
        
        // 没有图片
        if count == 0 {
            return CGSizeZero
        }
        // 一张图片
        if count == 1 {
            
//            // 从SDWebImage获取图片的缓存大小
            let key = status!.pictureURLs![0].absoluteString
            
            // image 不一定会被缓存下来
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
            // 图像不存在就设置默认大小
            var size = CGSize(width: 150, height: 120)
            
            // 判断图像是否存在
            if image != nil {
                size = image.size
            }
            
            // 对图像尺寸做判断，防止过宽过窄
            size.width = size.width < 40 ? 40 : size.width
            size.width = size.width > UIScreen.mainScreen().bounds.width ? 150 : size.width
            
    
            pictureLayout.itemSize = size
            
            return size
        }
        
        // 四张图片
        if count == 4 {
            
            let w = itemSize.width * 2 + margin
            return CGSize(width: w, height: w)
            
        }
        
        // 其他
        // 行数
        let row = (count - 1) / rowCount + 1
        let w = itemSize.width * CGFloat(rowCount) + margin * CGFloat(rowCount - 1)
        let h = itemSize.height * CGFloat(row) + margin * CGFloat(row - 1)
        
        return CGSize(width: w, height: h)
        
        
    }
    
    
    
    ///  图片布局
    private let pictureLayout = UICollectionViewFlowLayout()
    
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: pictureLayout)
        
        backgroundColor = UIColor.clearColor()
        
        // 注册课重用cell
        registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureViewCellID)
        
        self.dataSource = self
        
        self.delegate = self
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

// 在 swift 中，协议同样可以通过 extension 来写，可以将一组协议方法，放置在一起，便于代码维护和阅读！
extension StatusPictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    
    
    // 选中单元格的代理方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        print(status?.largePictureURLs)
    }
    
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.pictureURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusPictureViewCellID, forIndexPath: indexPath) as! StatusPictureViewCell
//        cell.backgroundColor = UIColor.lightGrayColor()
        
        cell.imageURL = status!.pictureURLs![indexPath.item]
        
        return cell
    }
    

}


class StatusPictureViewCell: UICollectionViewCell {
    
    var imageURL: NSURL? {
        didSet {
            iconView.sd_setImageWithURL(imageURL!)
        }
        
    }
    
    
    //MARK: 界面搭建
    private func setupUI() {
    
        contentView.addSubview(iconView)
        
        iconView.ff_Fill(contentView)
    }
    
    // MARK: 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: 懒加载
    private lazy var iconView: UIImageView = {
        
        let iv = UIImageView()
        
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        
//         超出边界的裁剪掉
        iv.clipsToBounds = true
        
        return iv
        
    }()
}


